package com.atguigu.service;

import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class PaymentService {

    //正常访问的接口
    public String payment_OK(){
        return "线程池：" + Thread.currentThread().getName()+ "调用成功😊";
    }

    /**
     * fallbackMethod超时或者报错，调用payment_Error_method这个方法
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "payment_Error_method",
    commandProperties = {
            //三秒没执行完毕就进入payment_Error_method方法(最大响应时间)
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")

    })
    public String paymnet_ERROR(Integer id) {
        log.info("SSHGUFgSUIfsdf:" +  id);
        //模拟超时5秒钟，肯定会进入兜底方法
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //模拟代码出错，看是否能到达兜底方法
//        int a = 10 / 0;
        return "线程池：" + Thread.currentThread().getName()+ "调用成功"+id+"😊";
    }

    public String payment_Error_method(Integer id){
        return "线程池：" + Thread.currentThread().getName()+ "访问超时，请稍后再试！！";
    }


    //自测服务熔断方法

    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",
    commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "1000"),//时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "20")//失败率，超过这个之后跳闸
    })
    public String paymentCircuitBreaker(Integer id){
        if(id < 0){
            throw new RuntimeException("ID不能为负数");
        }
        return Thread.currentThread().getName() + "访问成功！";
    }

    public String paymentCircuitBreaker_fallback(Integer id){

        return  "访问出错，ID不能为负数，请稍后再试！";
    }
}
